var strings = [];
var currentLanguageId = 'en';

function switchLanguage(languageId) {
	var language = {};
	$(strings).each(function (){
		if (this.lang == languageId) {
			language = this;
		}
	});
	
	$('span#options-button').text(language.optionsButton);
	$('span#built-with-label').text(language.builtWithLabel);
	
	$('[id*=unit]').each(function (){
		var unitName = $(this).val();
		var unit = 'undefined';
		var findUnit = unitName.toLowerCase();
		var unitBox = this;
	
		$.each(units, function () {
			var thisUnit = this;
			$.each(this.languages, function() {
				if (findUnit == this.value.toLowerCase()) {
					unit = thisUnit;
				}
			});
		});
		
		if (unit == 'undefined') {
			return;
		}
		
		$.each(unit.languages, function() {
			if (this.lang == languageId) {
				$(unitBox).val(this.value);
			}
		});
	});
	currentLanguageId = languageId;
	localStorage.setItem('lastLanguage', languageId);
}

function languagesLoadedListener() {
	if (units == undefined) {
		return;
	}
	if (strings.length == 0) {
		return;
	}
	var languageId = localStorage.getItem('lastLanguage');
	if (languageId != undefined) {
		if (languageId.length > 0) {
			switchLanguage(languageId);
		}
	}

}

$(document).ready(function () {
	$(document).on('languagesLoaded unitsLoaded', languagesLoadedListener);
	
	var pathname = window.location.pathname.substring(0, window.location.pathname.lastIndexOf("/") + 1);
    var origin = window.location.origin;

    if (!origin) {
        origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
    }

    var xmlLoc = origin + pathname + "data/strings.xml";
	
	//load language stuff
	$.ajax({
        type: "GET",
        url: xmlLoc,
        dataType: "xml",
        success: function (xml) {
            $xml = $(xml);
			$xml.find('language').each(function () {
				var language = {};
				language.lang = $(this).attr('id');
				language.optionsButton = HTMLescape($(this).find('button#options').text());
				language.builtWithLabel = HTMLescape($(this).find('label#built-with').text());
				strings.push(language);
			}).promise().done( function () {
				$(document).trigger('languagesLoaded');
			});
			
		}
	});
	
	$('span.language-selector').click(switchLanguageButtonListener);
	
});

function switchLanguageButtonListener(obj) {
	switchLanguage($(this).attr('id'));
}

function HTMLescape(html){
    return document.createElement('div')
        .appendChild(document.createTextNode(html))
        .parentNode
        .innerHTML
}
